import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    todos:JSON.parse(localStorage.getItem('vuex') || '[]'),
    showing:'all',
  },
  getters:{
    allChecked(state){
      if(state.todos.length===0){
        return false;
      }
      let flag=true;
      state.todos.map((v)=>{
        if(!v.status) flag=false;
      })
      return flag;
    },
    done(state){
      let count=0;
      state.todos.map((v)=>{
        if(!!v.status) count++;
      })
      return count;
    },
    total(state){
      return state.todos.length;
    },
    showTodos(state){
      if(state.showing==='all'){
        return state.todos;
      }else if(state.showing==='doing'){
        return state.todos.filter((v)=>{
          return !v.status;
        })
      }else if(state.showing==='done'){
        return state.todos.filter((v)=>{
          return !!v.status;
        })
      }
    }
  },
  mutations: {
    deleteDone(state){
      let doingItem=state.todos.filter((v)=>{
        return !v.status;
      })
      state.todos=doingItem;
    },
    addTodos:function(state,{payload}){
      state.todos.push(payload);
    },
    allCheck(state,flag){
      state.todos.map((v)=>{
        v.status=flag;
      });
    },
    deleteItem(state,i){
      state.todos.splice(i,1);
    },
    showItem(state,val){
      state.showing=val;
    },
    turnTo(state,i){
      state.todos.splice(i,1);
    },
    changeItem(state, payload){
      state.todos[payload.index]['text']=payload.text;
    },
    itemCheckChange(state,payload){
      state.todos[payload.index]['status']=!payload.check;
    }
  },
  actions: {
  },
  modules: {
  }
})
